package com.ssii.www.myproject.shiro.filters;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class TestPermissionAuthorizationFilter extends PermissionsAuthorizationFilter {
  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
    HttpServletRequest req = (HttpServletRequest) request;
    //获取当前用户
    Subject subject = this.getSubject(request, response);
    //判断是否认证
    if(subject.getPrincipal()==null){
      //没认证重定向到登陆页面
      this.saveRequestAndRedirectToLogin(request,response);
    }else{
      //暂时不判断ajax请求
      String unauthorizedUrl = this.getUnauthorizedUrl();
      if(StringUtils.isNotEmpty(unauthorizedUrl)){
        WebUtils.issueRedirect(request,response,unauthorizedUrl);
      }else{
        WebUtils.toHttp(response).sendError(401);
      }
    }
    return false;
  }
}
